const models = require('../db/db');
const express = require('express');
const router = express.Router();
const mysql = require('mysql');
const $sql = require('../db/sqlMap');

const conn = mysql.createConnection(models.mysql);
conn.connect();
// 查询全部
router.post('/findAll',(req,res)=>{
	const sel_email = $sql.cart.select;
	const params = req.body;
	conn.query(sel_email,params.id,(error, results)=>{
		if (error) {
			throw error;
		}
		console.log(results)
		if (results!=null) {
			res.send(results);  // -1 表示查询不到，用户不存在，即邮箱填写错误
		} 
	})
});

// 删除接口
router.post('/delAddress',(req,res)=>{
	const user = req.body;
	const sel_email = $sql.address.delete + " where confirmAddress_id = '" + user.id + "'";
	conn.query(sel_email,user.id, (error, results)=>{
		if (error) {
			throw error;
		}else{
			res.send({msg:'ok'}); 
		}
		
	})
});

// 添加收获地址
router.post('/AddAddress',(req,res)=>{
	const sel_email = $sql.address.insert;
	const user = req.body;
	conn.query(sel_email,[user.userName,user.userTel,user.userAddress,user.id],(error, results)=>{
		if (error) {
			throw error;
		}
		console.log(results)
		if (results!=null) {
			res.send(results);  // -1 表示查询不到，用户不存在，即邮箱填写错误
		} 
	})
});

// 查询全部收获地址
router.get('/findAddress',(req,res)=>{
	const sel_email = $sql.address.select;
	const user = req.body;
	conn.query(sel_email,user.id,(error, results)=>{
		if (error) {
			throw error;
		}
		console.log(results)
		if (results!=null) {
			res.send(results);  // -1 表示查询不到，用户不存在，即邮箱填写错误
		} 
	})
});

// 删除接口
router.post('/delCart',(req,res)=>{
	const user = req.body;
	const sel_email = $sql.cart.delete + " where cart_id = '" + user.id + "'";
	conn.query(sel_email,user.id, (error, results)=>{
		if (error) {
			throw error;
		}else{
			res.send({msg:'ok'}); 
		}
		
	})
});

//修改购物车商品数量
router.post('/updateNum',(req,res)=>{
	const user = req.body;
	const sel_email = $sql.cart.update;
	conn.query(sel_email,[user.cart_num,user.cart_name], (error, results)=>{
		if (error) {
			throw error;
		}else{
			res.send({msg:'ok'}); 
		}
		
	})
});

// 加入购物车接口
router.post('/addCart', (req, res) => {
	const params = req.body;
	const add_sql = $sql.cart.add;
	const selGoodsName=$sql.cart.selGoodsName+ " where cart_name = '" + params.cart_name + "'and id='"+params.id+"'";
	// const selectNum=$sql.goods.selectNum;
	const update = $sql.cart.update		
	
	conn.query(selGoodsName, [params.cart_name,params.id],(err, rst) => {
		if (err) {
			console.log(err);
		} 	
		if(rst[0]!=null){			
			conn.query(update, [rst[0].cart_num+1,params.cart_name],  (err, rst) => {
				if (err) {
					console.log(err);
				} else{
					res.send({msg:'1'}); 
				}
			});	
		}else{
			conn.query(add_sql, [params.cart_name, params.cart_img, params.cart_price,params.cart_num, params.goods_id, params.id], (err, rst) => {
				if (err) {
					console.log(err);
				} else{
					res.send({msg:'0'});
				}
			});	
		}
	});	

});


module.exports = router;